/* ============================================================================ */
/*                    IMPORT DATA AND PREPARE WEIGHTS                           */
/* ============================================================================ */

clear all

* Load matched sample with nearest neighbor (NN) weights
use "$output\matched_sample_nn.dta", clear

* Keep relevant time periods
keep if mdate < mofd(date("20200101","YMD"))
keep if mdate > mofd(date("20131231","YMD"))

* Restrict to quarterly observations (March, June, September, December)
keep if inlist(datemonth, 3, 6, 9, 12)

* Convert monthly date to quarterly format
format mdate %tm
gen qdate = qofd(dofm(mdate))
format qdate %tq
sort siren qdate

* Add fixed effect labels
estadd local yearfirm "Y", replace   
estadd local mdateFE "Y", replace  

* Keep only necessary variables
keep qdate siren weight year

* Save weight data for merging later
save "$output\weight_quarter.dta", replace


/* ============================================================================ */
/*                      IMPORT SHIFT-SHARE DATASET                             */
/* ============================================================================ */

import delimited "$input\shift_share_data_set.csv", clear

* Convert date variables
gen time = date(date, "YMD")
gen qdate = qofd(time)
format time %td
format qdate %tq

gen startoutsideloan = date(datestart, "YMD")
gen qstartoutsideloan = qofd(startoutsideloan)
format startoutsideloan %td
format qstartoutsideloan %tq

sort siren qdate

* Define post-treatment periods for P2P and control groups
gen p2pqtrcapturing = qdate >= qstartoutsideloan if p2p == 1
gen outsideloanqtrcapturing = qdate >= qstartoutsideloan if p2p == 0
gen p2pqtrcapturingstrict = qdate > qstartoutsideloan if p2p == 1
gen outsideloanqtrcapturings = qdate > qstartoutsideloan if p2p == 0

* Compute relative quarter difference from start date
gen deltaquarter = qdate - qstartoutsideloan
gen deltaqdummy = deltaquarter >= -4 & deltaquarter <= 8
replace deltaqdummy = . if deltaquarter == .

/* ============================================================================ */
/*                      FILTER AND CLEAN INDUSTRY DATA                         */
/* ============================================================================ */

* Keep only firms in the t-test sample
merge m:1 siren using "$output\ifp_ttest_siren_list.dta", keepusing(siren)
keep if _merge == 3
drop _merge

* Aggregate industry classifications
replace industry = "public" if inlist(industry, "P", "Q", "R", "S")
replace industry = "DE" if inlist(industry, "D", "E")
replace industry = "FL" if inlist(industry, "F", "L")

* Drop industries not relevant for analysis
drop if inlist(industry, "A", "K", "O", "B", "DE", "0000Z")

* Generate industry group
egen industry10 = group(industry)

* Standardize ratings
replace rating = "3A" if rating == "3++"
replace rating = "3B" if rating == "3+"
replace rating = "3C" if rating == "3"
replace rating = "4A" if rating == "4+"
replace rating = "4B" if rating == "4"
replace rating = "5A" if rating == "5+"
replace rating = "5B" if rating == "5"

encode rating, gen(ratinge)
replace ratinge = ratinge - 1
replace ratinge = 13 if ratinge == 0

* Set time series format
tsset siren qdate, quarterly

* Keep relevant time periods
keep if qdate < qofd(date("20200101", "YMD"))
keep if qdate > qofd(date("20131231", "YMD"))

* Save processed dataset
tempfile dataset1
save `dataset1'

/* ============================================================================ */
/*                      PREPARE MAIN DATASET                                   */
/* ============================================================================ */

use "$output\ifp_scrapped_aggregated_industries_modified.dta", clear

* Restrict to quarterly observations (March, June, September, December)
keep if inlist(datemonth, 3, 6, 9, 12)

* Convert monthly date to quarterly format
format mdate %tm
gen qdate = qofd(dofm(mdate))
format qdate %tq

* Generate loan variables
gen lloan = log(ltloan + bm + bi)
gen lloanfilled = lloan
gen total_loan = stloan + ltloan + bm + bi + oc
sort siren qdate

* Generate credit line dummy
preserve
keep if delta < 0
collapse (sum) co, by(siren)
gen codummy = co > 0
drop co
save "$output\data_co_dummy.dta", replace
restore

* Standardize rating categories
egen ratingint = group(rating)
replace ratingint = ratingint - 1
replace ratingint = 13 if ratingint == 0

* Merge with credit line dummy
merge m:1 siren using "$output\data_co_dummy.dta"

* Label variables
label var r1filled        "Working capital"
label var r3filled        "EBIT"
label var r5filled        "Sales"
label var r12filled       "Investment"
label var r13filled       "Debt"
label var logassets_filled "Total Assets"
label var logemployees    "Employment"
label var r_collateral_filled "Tangible assets"
label var rdcostsfilled   "R&D costs filled"
label var ratingint       "Rating"
label var codummy         "$\mathbbm{1}$(Credit Line)"

global control `"r1filled r3filled r5filled r12filled r13filled logassets_filled logemployees r_collateral_filled ratingint"'

* Keep only necessary variables
keep qdate siren lloanfilled lloan* ltloan total_loan $control

/* ============================================================================ */
/*                      MERGE DATASETS AND FINAL CLEANUP                        */
/* ============================================================================ */

merge 1:1 siren qdate using `dataset1', nogen

* Keep only observations from 2014Q1 onward
keep if qdate >= tq(2014q1)

/* ============================================================================ */
/*                      CREATE FIXED EFFECT GROUP VARIABLES                    */
/* ============================================================================ */

egen ind_qtr = group(industry10 qdate)
egen size_qtr = group(size qdate)
egen reg_qtr = group(region qdate)
egen rat_qtr = group(ratinge qdate)

* Generate post-treatment indicators
replace outsideloanqtrcapturing = 0 if outsideloanqtrcapturing == .
replace p2pqtrcapturing = 0 if p2pqtrcapturing == .
gen post = p2pqtrcapturing + outsideloanqtrcapturing
replace outsideloanqtrcapturings = 0 if outsideloanqtrcapturings == .
replace p2pqtrcapturingstrict = 0 if p2pqtrcapturingstrict == .
gen poststrict = p2pqtrcapturingstrict + outsideloanqtrcapturings

* Set time series format again after data modifications
tsset siren qdate, quarterly
sort siren qdate

/* ============================================================================ */
/*                      LOGGING AND CONTROL VARIABLES                          */
/* ============================================================================ */

capture log close
log using "$logs\shift_share_count.log", replace

* Generate control dummies for missing values
foreach var in $control {
    gen `var'_0 = `var'
    replace `var'_0 = 0 if `var' == .
    gen dum_`var' = (`var' == .)
}

global control_0 `"*_0 dum_*"'
	
/* ============================================================================ */
/*                          COL1: MAIN ESTIMATIONS                              */
/* ============================================================================ */

/* Define Score Variable Using Count of Loans */
gen scoredeltap2p = secured02

/* Keep This Score Fixed by SIREN and Store at Quarter When P2P Loan Was Granted */
replace scoredeltap2p = . if p2pqtrcapturing == 0
replace scoredeltap2p = . if !(L.p2pqtrcapturing == 0 & p2pqtrcapturing == 1)
by siren: carryforward scoredeltap2p, replace
by siren: replace scoredeltap2p = scoredeltap2p[_N]

/* Define Score Variable for Control Group */
gen scoredeltacontran = secured02
replace scoredeltacontran = . if outsideloanqtrcapturing == 0
replace scoredeltacontran = . if !(L.outsideloanqtrcapturing == 0 & outsideloanqtrcapturing == 1)
by siren: carryforward scoredeltacontran, replace
by siren: replace scoredeltacontran = scoredeltacontran[_N]

/* Merge Scores for Both Groups */
gen scoredeltaboth = scoredeltacontran if p2p == 0
replace scoredeltaboth = scoredeltap2p if p2p == 1
gen scoredeltapost = scoredeltaboth * post

/* ============================================================================ */
/*          CONTROL VARIABLE: SHIFT-SHARE CREDIT SUPPLY IN VOLUME              */
/* ============================================================================ */

/* Define Shift-Share Credit Supply for P2P */
gen volloanp2pv = logloan02
replace volloanp2pv = . if p2pqtrcapturing == 0
replace volloanp2pv = . if !(L.p2pqtrcapturing == 0 & p2pqtrcapturing == 1)
by siren: carryforward volloanp2pv, replace
by siren: replace volloanp2pv = volloanp2pv[_N]

/* Define Shift-Share Credit Supply for Control Group */
gen volloancontranv = logloan02
replace volloancontranv = . if outsideloanqtrcapturing == 0
replace volloancontranv = . if !(L.outsideloanqtrcapturing == 0 & outsideloanqtrcapturing == 1)
by siren: carryforward volloancontranv, replace
by siren: replace volloancontranv = volloancontranv[_N]

/* Merge Credit Supply Controls for Both Groups */
gen volloanbothv = volloancontranv if p2p == 0
replace volloanbothv = volloanp2pv if p2p == 1
gen volloanv = volloanbothv * post

/* ============================================================================ */
/*                  MERGE DATA TO GET WEIGHTS FROM PSM MATCHING                */
/* ============================================================================ */

merge 1:1 siren qdate using "$output\weight_quarter.dta", nogen keep(1 3)

/* ============================================================================ */
/*                    COL1: BASELINE IV REGRESSION                              */
/* ============================================================================ */

eststo col1: ivreghdfe lloan (p2pqtrcapturing = scoredeltapost) post volloanv $control_0 ///
if deltaqdummy, cl(siren) a(i.qdate i.siren)

* Count number of firms in treatment and control groups
qui levelsof siren if p2p == 1 & e(sample), local(sirens_p2p1)
qui levelsof siren if p2p == 0 & e(sample), local(sirens_p2p0)
local num_sirens_p2p1: word count `sirens_p2p1'
local num_sirens_p2p0: word count `sirens_p2p0'

* Store regression statistics
estadd local siren      "Y", replace
estadd local control    "Y", replace
estadd local qdate      "Y", replace
estadd local indqtr     "N", replace
estadd local regqtr     "N", replace
estadd local ratqtr     "N", replace
estadd local sizeqtr    "N", replace
estadd local num_sirens_p2p1 `num_sirens_p2p1', replace
estadd local num_sirens_p2p0 `num_sirens_p2p0', replace
estadd scalar f2 = e(widstat)
gen sample = e(sample)

/* ============================================================================ */
/*             COL1C: INDUSTRY FIXED EFFECTS                                   */
/* ============================================================================ */

eststo col1c: ivreghdfe lloan (p2pqtrcapturing = scoredeltapost) post volloanv $control_0 ///
if deltaqdummy, cl(siren) a(i.ind_qtr i.siren)

estadd local siren     "Y", replace
estadd local control   "Y", replace
estadd local qdate     "N", replace
estadd local indqtr    "Y", replace
estadd local regqtr    "N", replace
estadd local ratqtr    "N", replace
estadd local sizeqtr   "N", replace
estadd scalar f2 = e(widstat)

/* ============================================================================ */
/*             COL1D: REGION FIXED EFFECTS                                     */
/* ============================================================================ */

eststo col1d: ivreghdfe lloan (p2pqtrcapturing = scoredeltapost) post volloanv $control_0 ///
if deltaqdummy, cl(siren) a(i.reg_qtr i.siren)

estadd local siren     "Y", replace
estadd local control   "Y", replace
estadd local qdate     "N", replace
estadd local indqtr    "N", replace
estadd local regqtr    "Y", replace
estadd local ratqtr    "N", replace
estadd local sizeqtr   "N", replace
estadd scalar f2 = e(widstat)

/* ============================================================================ */
/*             COL1E: SIZE FIXED EFFECTS                                       */
/* ============================================================================ */

eststo col1e: ivreghdfe lloan (p2pqtrcapturing = scoredeltapost) post volloanv $control_0 ///
if deltaqdummy, cl(siren) a(i.size_qtr i.siren)

estadd local siren     "Y", replace
estadd local control   "Y", replace
estadd local qdate     "N", replace
estadd local indqtr    "N", replace
estadd local regqtr    "N", replace
estadd local ratqtr    "Y", replace
estadd local sizeqtr   "N", replace
estadd scalar f2 = e(widstat)

/* ============================================================================ */
/*             COL1F: RATING FIXED EFFECTS                                     */
/* ============================================================================ */

eststo col1f: ivreghdfe lloan (p2pqtrcapturing = scoredeltapost) post volloanv $control_0 ///
if deltaqdummy, cl(siren) a(i.rat_qtr i.siren)

estadd local siren     "Y", replace
estadd local control   "Y", replace
estadd local qdate     "N", replace
estadd local indqtr    "N", replace
estadd local regqtr    "N", replace
estadd local ratqtr    "N", replace
estadd local sizeqtr   "Y", replace
estadd scalar f2 = e(widstat)


/* ============================================================================ */
/*               ROBUSTNESS CHECK: ADDITIONAL IV REGRESSIONS                    */
/* ============================================================================ */

foreach j in 3 4 { 

    * Drop previously generated variables to avoid conflicts
    drop scoredelta* volloan*

    * Generate the secured loan variable for P2P loans
    gen scoredeltap2p = secured0`j'

    * Keep this score fixed by SIREN and store it at the quarter when P2P loan was granted
    replace scoredeltap2p = . if p2pqtrcapturing == 0
    replace scoredeltap2p = . if !(L.p2pqtrcapturing == 0 & p2pqtrcapturing == 1)
    by siren: carryforward scoredeltap2p, replace
    by siren: replace scoredeltap2p = scoredeltap2p[_N]

    * Generate the secured loan variable for control group (traditional loans)
    gen scoredeltacontran = secured0`j'
    replace scoredeltacontran = . if outsideloanqtrcapturing == 0
    replace scoredeltacontran = . if !(L.outsideloanqtrcapturing == 0 & outsideloanqtrcapturing == 1)
    by siren: carryforward scoredeltacontran, replace
    by siren: replace scoredeltacontran = scoredeltacontran[_N]

    * Merge secured loan values for both groups
    gen scoredeltaboth = scoredeltacontran if p2p == 0
    replace scoredeltaboth = scoredeltap2p if p2p == 1
    gen scoredeltapost = scoredeltaboth * post

    /* ============================================================================ */
    /*      CONTROL VARIABLE: SHIFT-SHARE CREDIT SUPPLY IN VOLUME                  */
    /* ============================================================================ */

    * Generate log credit supply for P2P loans
    gen volloanp2pv = logloan0`j'
    replace volloanp2pv = . if p2pqtrcapturing == 0
    replace volloanp2pv = . if !(L.p2pqtrcapturing == 0 & p2pqtrcapturing == 1)
    by siren: carryforward volloanp2pv, replace
    by siren: replace volloanp2pv = volloanp2pv[_N]

    * Generate log credit supply for control group
    gen volloancontranv = logloan02
    replace volloancontranv = . if outsideloanqtrcapturing == 0
    replace volloancontranv = . if !(L.outsideloanqtrcapturing == 0 & outsideloanqtrcapturing == 1)
    by siren: carryforward volloancontranv, replace
    by siren: replace volloancontranv = volloancontranv[_N]

    * Merge credit supply values for both groups
    gen volloanbothv = volloancontranv if p2p == 0
    replace volloanbothv = volloanp2pv if p2p == 1
    gen volloanv = volloanbothv * post

    /* ============================================================================ */
    /*                       REGRESSION: IV ESTIMATIONS                            */
    /* ============================================================================ */

    eststo col`j': ivreghdfe lloan (p2pqtrcapturing = scoredeltapost) post volloanv $control_0 ///
        if deltaqdummy, cl(siren) a(i.qdate i.siren)

    * Count number of firms in treatment and control groups
    qui levelsof siren if p2p == 1 & e(sample), local(sirens_p2p1)
    qui levelsof siren if p2p == 0 & e(sample), local(sirens_p2p0)
    local num_sirens_p2p1: word count `sirens_p2p1'
    local num_sirens_p2p0: word count `sirens_p2p0'

    * Store regression statistics
    estadd local siren       "Y", replace
    estadd local control     "Y", replace
    estadd local qdate       "Y", replace
    estadd local indqtr      "N", replace
    estadd local regqtr      "N", replace
    estadd local ratqtr      "N", replace
    estadd local sizeqtr     "N", replace
    estadd local num_sirens_p2p1 `num_sirens_p2p1', replace
    estadd local num_sirens_p2p0 `num_sirens_p2p0', replace
    estadd scalar f2 = e(widstat)

}

********************************************************************************

/* ============================================================================ */
/*                        EXPORT TABLE I1                                       */
/* ============================================================================ */

label var scoredeltapost "Secured ratio $\times$ Post"
label var post "Post"
label var p2pqtrcapturing "FinTech $\times$ Post"
label var volloanv "Credit supply  $\times$ Post"

esttab col1 col3 col4 col1c col1d col1e col1f using "$tables\shift-share_robustness.tex", ///
    replace star(* 0.10 ** 0.05 *** 0.01) nomtitles fragment gap booktabs label nonote noobs eqlabels(,none) ///
    b(%9.3f) se(%9.3f) stats(siren qdate control indqtr regqtr ratqtr sizeqtr N f2, ///
    labels("Firm FE" "Quarter FE" "Controls" "Industry $\times$ Year-quarter FE"  ///
    "Region $\times$ Year-quarter FE" "Rating $\times$ Year-quarter FE" "Size $\times$ Year-quarter FE" ///
    "\midrule Observations" "F-stat")) ///
    layout("\multicolumn{1}{c}{@}" "\multicolumn{1}{c}{@}" "\multicolumn{1}{c}{@}" ///
           "\multicolumn{1}{c}{@}" "\multicolumn{1}{c}{@}" ///
           "\multicolumn{1}{c}{@}" "\multicolumn{1}{c}{@}" "\multicolumn{1}{c}{@}" "\multicolumn{1}{c}{@}") ///
    fmt(%9.0fc %9.0fc %9.0fc %9.0fc %9.0fc %9.0fc %9.0fc %9.0fc %9.3fc)) ///
    keep(p2pqtrcapturing post volloanv) ///
    order(p2pqtrcapturing post volloan) ///
    mgroups("log(Long-term credit)" , pattern(1 0 0 0 0 0 0) prefix(\multicolumn{@span}{c}{)  suffix(}) span erepeat(\cmidrule(lr){@span}))

log close

